package com.example.controller;


import com.example.entity.LoginRequestDTO;
import com.example.entity.Result;
import com.example.entity.User;
import com.example.service.IUserService;
import com.example.service.LoginService;
import com.example.utils.GeneratorCodeMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;

@RestController
@RequestMapping
public class RegisterController {
    @Resource
    private IUserService userService;

    @Autowired
    private LoginService loginService;
    @Autowired
    private PasswordEncoder passwordEncoder;


//    注册
    @PostMapping("/register")
    public Result<?> register(@RequestBody LoginRequestDTO user){
        if(userService.getUserByUsername(user.getUsername())!=null){
            return Result.error(GeneratorCodeMsg.USER_EXIST);
        }
        if(user.getUsername().isEmpty()){
            return Result.error(GeneratorCodeMsg.USERNAME_NOT_IS_NULL);
        }
        if(user.getPassword().isEmpty()){
            return Result.error(GeneratorCodeMsg.PASSWORD_NOT_IS_NULL);
        }
        User user1 = new User();
        user1.setUsername(user.getUsername());
//        密码加密
        user1.setPassword(passwordEncoder.encode(user.getPassword()));
        user1.setCreateTime(LocalDateTime.now());
        user1.setUpdateTime(LocalDateTime.now());
        user1.setSex(0);
        user1.setIdentify(1);
        userService.save(user1);
        return Result.success();
    }

    @PostMapping("/login")
    public Result<?> login(@RequestBody User user){ return loginService.login(user);}



}
